'use strict';

webappApp.factory('queue', function() {
  var executing = [],
  queued = [],

  status = {
    queued: queued.length,
    executing: executing.length
  };
  return {
    push: function (task) {
      if (executing.length >= this.capacity) {
        queued.push(task);
        status.queued = queued.length;
      } else {
        executing.push(task);
        status.executing = executing.length;
        queued.remove(task);
        status.queued = queued.length;
        task.call(task);
      }
    },
    pop: function (task) {
      if (task) {
        executing.remove(task);
      } else if (executing.length > 0) {
        executing.pop();
      }
      if (executing.length < this.capacity &&
          queued.length) {
        this.push(queued.pop());
      }
      status.executing = executing.length;
      status.queued = queued.length;
    },
    clear: function () {
      status.queued = queued.length = 0;
      status.executing = executing.length = 0;
    },
    capacity: 5,
    status: status
  };
});
